/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.system.controller;


import com.fasterxml.jackson.annotation.JsonFormat;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.common.web.Util;
import com.koron.system.domain.Message;
import com.koron.system.service.api.MessageService;
import com.koron.system.utils.BusinessCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Api(tags = "message", description = "消息接口类")
@RestController
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private MessageService messageService;

    @Autowired
    private Util util;


    @ApiOperation("保存消息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "新增不传，修改必传", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "title", value = "消息标题", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "content", value = "消息内容", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "receiverCode", value = "接收人code", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/save.htm", method = RequestMethod.POST)
    public MessageBean<Integer> save(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore Message message) {
        if (null == user) {
            MessageBean<Integer> msg = new MessageBean<>();
            msg.setCode(BusinessCode.NOT_LOGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return msg;
        }
        Date time = new Date();
        message.setUpdateTime(time);
        message.setUpdateUser(user.getName());
        MessageBean<Integer> msg = messageService.save(message);
        return msg;
    }


    @ApiOperation("根据主键删除消息，可批量删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "消息Id,多个之间用，分开", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/batchDelete.htm", method = RequestMethod.POST)
    public MessageBean<Integer> batchDelete(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String ids) {
        MessageBean<Integer> msg = new MessageBean<>();
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LOGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return msg;
        }
        if (StringUtils.isEmpty(ids)) {
            msg.setCode(BusinessCode.MESSAGE_EMPTY_CHANGE_DATA.getCode());
            msg.setDescription(BusinessCode.MESSAGE_EMPTY_CHANGE_DATA.getDescription());
            return msg;
        }
        String[] idArray = ids.split("[,，]");
        Integer value = messageService.batchDelete(Arrays.asList(idArray));
        if (value > 0) {
            msg.setData(value);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("删除成功");
            return msg;
        } else {
            msg.setData(value);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("删除失败");
            return msg;
        }
    }


    @ApiOperation("根据主键获取消息详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "消息Id", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/details.htm", method = RequestMethod.POST)
    public MessageBean<Message> details(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = true) final String id) {
        MessageBean<Message> msg = new MessageBean<>();
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LOGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return msg;
        }
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.MESSAGE_EMPTY_CHANGE_DATA.getCode());
            msg.setDescription(BusinessCode.MESSAGE_EMPTY_CHANGE_DATA.getDescription());
            return msg;
        }
        Message message = messageService.queryOne(id);
        msg.setCode(BusinessCode.SUCCESS.getCode());
        msg.setDescription("获取消息详情成功");
        msg.setData(message);
        return msg;
    }


    @ApiOperation("获取消息列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "receiverCode", value = "接收人code,PC端不传，App必传", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键词", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/list.htm", method = RequestMethod.POST)
    public MessageBean<DataBean<Message>> list(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) final String receiverCode, @RequestParam(required = false) final @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
    @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime, @RequestParam(required = false) final @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
                                               @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime,@RequestParam(required = false) String keyword, @RequestParam(required = true) Integer page, @RequestParam(required = true) Integer pageSize) {
        MessageBean<DataBean<Message>> msg = new MessageBean<>();
        if (null == user) {
            if (StringUtils.isNotEmpty(receiverCode)) {
                List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(receiverCode, null).getData();
                if (null != staffBeanList && staffBeanList.size() > 0)
                    user = staffBeanList.get(0);
            }
        }
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LOGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return msg;
        }
        Integer start = null;
        if (page == null || page <= 0) {
            page = 1;
            if (pageSize == null || pageSize <= 0) {
                pageSize = 15;
            }
        }
        start = (page <= 1) ? 0 : (page - 1) * pageSize;
        msg = messageService.queryByCondition(user.getCode(), startTime, endTime, start, pageSize,keyword);
        msg.getData().setPageNo(page);
        return msg;

    }


    @ApiOperation("根据主键处理消息为已读状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "消息Id", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/updateIsRead.htm", method = RequestMethod.POST)
    public MessageBean<Integer> updateIsRead(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam final String id) {
        MessageBean<Integer> msg = new MessageBean<>();
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LOGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return msg;
        }
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.MESSAGE_EMPTY_CHANGE_DATA.getCode());
            msg.setDescription(BusinessCode.MESSAGE_EMPTY_CHANGE_DATA.getDescription());
            return msg;
        }
        msg = messageService.updateIsRead(id);
        return msg;
    }

    @ApiOperation("获取是否有未读消息，待办任务，待审流程")
    @RequestMapping(value = "/getAllState.htm", method = RequestMethod.POST)
    public MessageBean<Integer> getAllState(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user) {
        MessageBean<Integer> msg = new MessageBean<>();
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LOGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return msg;
        }
        msg = ADOConnection.runTask(factory -> messageService.getAllState(factory,user), MessageBean.class);
        return msg;
    }

}
